import { history, Link } from 'umi';
import styles from './index.less';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { allGet } from '@/services/pc';
import { Popover } from 'antd';
import { QRCodeSVG } from 'qrcode.react';
interface Props {
  ids: any[];
  currentId: any;
  onClose?: (e) => void;
  showClose?: boolean;
}

const QrCode = () => {
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  useEffect(() => {
    setQrCodeUrl(window.location.href);
  }, []);
  return (
    <div className={styles.qrCode}>
      <QRCodeSVG value={qrCodeUrl} />
      <span className={styles.title}>微信扫码分享</span>
    </div>
  );
};

const WorkDetail: React.FC<Props> = (props) => {
  const currentIndexRef = useRef(0);
  const [data, setData] = useState<any>({});
  const [allData, setAllData] = useState<any>({});
  const [classWorks, setClassWorks] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(() => {
    if (props.ids.length > 0) {
      const index = props.ids.findIndex((item) => item === props.currentId);
      currentIndexRef.current = index > -1 ? index : 0;
      console.log(currentIndexRef.current, 3434343);
      return index > -1 ? index : 0;
    }
    return 0;
  });

  const getClassWorks = async (classid) => {
    const params: any = {
      mod: 'busywork',
      do: 'list',
      perpage: 3,
      page: 1,
      classid,
      version: 'pc1.0',
    };
    const response = await allGet({ params });
    setClassWorks(response?.data?.list || []);
  };
  const getDetail = async (bid) => {
    setLoading(true);
    const response = await allGet({ params: { mod: 'busywork', bid, version: 'pc1.0' } });
    setData(response?.data || {});
    setAllData(response || {});
    setLoading(false);
  };

  useEffect(() => {
    getDetail(props.currentId);
  }, []);
  const handleClose = (e) => {
    props?.onClose?.(e);
  };

  const videoRef = useRef<HTMLVideoElement>(null);
  useEffect(() => {
    return () => {
      videoRef.current?.pause?.();
    };
  }, []);

  const handleGoClass = () => {
    window.open(`/center/courses/detail/${data.classid}`);
  };

  const handlePrev = () => {
    if (loading) return;
    document.getElementsByClassName('ant-modal-wrap')?.[0]?.scrollTo({
      left: 0,
      top: 0,
    });
    setCurrentIndex(currentIndex - 1);
    const id = props.ids[currentIndex - 1];
    getDetail(id);
    window.history.replaceState(null, '', `/center/work/detail/${id}`);
  };

  const handleNext = () => {
    if (loading) return;
    document.getElementsByClassName('ant-modal-wrap')?.[0]?.scrollTo({
      left: 0,
      top: 0,
    });
    setCurrentIndex(currentIndex + 1);
    const id = props.ids[currentIndex + 1];
    getDetail(id);
    window.history.replaceState(null, '', `/center/work/detail/${id}`);
  };

  const renderFile = () => {
    if (data.pic) {
      return <img className={styles.img} src={data.pic} alt="" />;
    }
    if (data.videourl) {
      return (
        <video
          ref={videoRef}
          className={styles.video}
          autoPlay
          controls
          controlsList="nodownload"
          disablePictureInPicture
          preload="metadata"
          muted
          loop
          src={data.videourl}
        />
      );
    }
    if (data.videoid && !data.videourl) {
      return (
        <div className={styles.zhuanmazhong}>
          <i className={styles.icon} />
          <span className={styles.text}>视频正在转码，稍后来查看</span>
        </div>
      );
    }

    return null;
  };
  const keydownPrev = () => {
    if (loading) return;
    if (currentIndexRef.current === 0) return;
    currentIndexRef.current = currentIndexRef.current - 1;
    document.getElementsByClassName('ant-modal-wrap')?.[0]?.scrollTo({
      left: 0,
      top: 0,
    });
    setCurrentIndex(currentIndexRef.current);
    const id = props.ids[currentIndexRef.current];
    getDetail(id);
    window.history.replaceState(null, '', `/center/work/detail/${id}`);
  };
  const keydownNext = () => {
    if (loading) return;
    if (currentIndexRef.current === props.ids.length - 1) return;
    currentIndexRef.current = currentIndexRef.current + 1;
    document.getElementsByClassName('ant-modal-wrap')?.[0]?.scrollTo({
      left: 0,
      top: 0,
    });
    setCurrentIndex(currentIndexRef.current);
    const id = props.ids[currentIndexRef.current];
    getDetail(id);
    window.history.replaceState(null, '', `/center/work/detail/${id}`);
  };

  const keydown = (event) => {
    if (event.keyCode === 37) {
      keydownPrev();
    }
    if (event.keyCode === 39) {
      keydownNext();
    }
    if (event.keyCode === 32) {
      event.preventDefault();
      if (videoRef.current?.paused) {
        videoRef.current.play();
      } else {
        videoRef.current?.pause();
      }
    }
  };

  const handleShowOtherWork = (id) => {
    getDetail(id);
    window.history.replaceState(null, '', `/center/work/detail/${id}`);
  };

  useEffect(() => {
    document.addEventListener('keydown', keydown);
    return () => {
      document.removeEventListener('keydown', keydown);
    };
  }, []);

  const goToUser = () => {
    window.open(`/personal?uid=${data.uid}`);
  };
  return (
    <div className={styles.WorkDetail}>
      <div className={styles.left}>
        <div className={styles.content}>
          {renderFile()}
          {props.ids.length > 1 && (
            <>
              {currentIndex !== 0 && <i className={styles.prev} onClick={handlePrev} />}
              {currentIndex !== props.ids.length - 1 && (
                <i className={styles.next} onClick={handleNext} />
              )}
            </>
          )}
        </div>
      </div>
      <div className={styles.right}>
        {props.showClose && <i className={styles.close} onClick={handleClose} />}
        <img src={data.avatar} className={styles.avatar} onClick={goToUser} />
        <div className={styles.name}>{data.username}</div>
        <div className={styles.number}>学号：{data.studentnum}</div>
        {allData?.userworks?.length > 0 && (
          <div className={styles.othersWork}>
            <div className={styles.header}>
              <div className={styles.title}>其他作品</div>
              <div className={styles.more} onClick={goToUser}>
                查看更多 <i className={styles.icon} />
              </div>
            </div>
            <div className={styles.body}>
              {allData?.userworks?.map((item) => {
                return (
                  <div
                    className={styles.item}
                    key={item.bid}
                    onClick={() => handleShowOtherWork(item.bid)}
                  >
                    <img src={item.thumb} alt="" />
                  </div>
                );
              })}
            </div>
          </div>
        )}
        <div className={styles.line} />
        <div className={styles.xlWrapper}>
          <div className={styles.liulangliang}>浏览量 {data.viewnum}</div>
          <div className={styles.shijian}>{data.dateline}</div>
        </div>
        <div className={styles.buttons}>
          {data.downfile && (
            <a
              className={classNames(styles.button, styles.ywj)}
              href={data.downfile}
              target="_blank"
              rel="noreferrer"
            >
              <div className={styles.icon} />
              下载源文件
            </a>
          )}

          <Popover
            overlayClassName={styles.sharepopover}
            placement="left"
            trigger="hover"
            zIndex={9999}
            content={<QrCode />}
            title={() => null}
          >
            <div className={classNames(styles.button, styles.fx)}>
              <div className={styles.icon} />
              分享
            </div>
          </Popover>
        </div>
        <div className={styles.line} />
        <div className={styles.teacherWrapper}>
          <div className={styles.teacherWrapperleft}>
            <img
              className={styles.touxiang}
              src={data.teacheravatar}
              onClick={() => window.open(`/teachers/detail/${allData?.course?.uid}`)}
            />
            <div className={styles.info}>
              <div
                className={styles.infotitle}
                onClick={() => window.open(`/teachers/detail/${allData?.course?.uid}`)}
              >
                {data.teacher} 老师的评分：
              </div>
              <div className={styles.shijian}>{data.scoreline || '-'}</div>
            </div>
          </div>
          <div className={styles.teacherWrapperright}>
            {data.score != 0 ? (
              <i className={classNames(styles.fenshu, styles[`fenshu${data.score}`])} />
            ) : (
              <div className={styles.weipingfeng}>未评分 </div>
            )}
          </div>
        </div>
        <div className={styles.classWrapper}>
          <div className={styles.currentClass} onClick={handleGoClass}>
            <img className={styles.currentimg} src={data.classthumb} />
            <div className={styles.currentClassright}>
              <div className={styles.currentClassName}>{data.coursename}</div>
              <div className={styles.currentClassPrice}>¥{data.courseprice}</div>
            </div>
          </div>
          {allData?.courseworks?.length > 0 && (
            <div className={styles.otherClass}>
              <div className={styles.header}>
                <div className={styles.title}>本课程作业合集</div>
                <div
                  className={styles.more}
                  onClick={() => {
                    window.open(
                      `/center/detail/works/1?classid=${
                        data.classid
                      }&classname=${encodeURIComponent(data.coursename)}&order=bid`,
                    );
                  }}
                >
                  查看集合
                  <div className={styles.icon} />
                </div>
              </div>
              <div className={styles.body}>
                {allData?.courseworks?.map((item: any) => {
                  return (
                    <div
                      key={item.bid}
                      className={styles.item}
                      onClick={() => handleShowOtherWork(item.bid)}
                    >
                      <img src={item.thumb} />
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default WorkDetail;
